﻿using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //退货单控制器
    public class ReturnBillController : Controller
    {
        //
        // GET: /ProductProcedure/

        private readonly IReturnBillService operationServiceImpl = ServiceLocator.Instance.GetService<IReturnBillService>();

        public ActionResult Index()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public ActionResult AddAndConfirm(ReturnBillDto roductInBillDto)
        {
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
            //保存(或更新)
            var aa = Add(roductInBillDto) as ContentResult;
            string actionResult = aa.Content.ToString();
            Guid tempId = Guid.Empty;
            if (Guid.TryParse(actionResult.ToString(), out tempId))
            {
                if (tempId.Equals(Guid.Empty))//有超过库存数量的单据
                {
                    return Content("-3");
                }
                roductInBillDto.Id = tempId;
            }
            else
            {
                return Content(actionResult.ToString());
            }
            //提交
            if (isConfirm)
            {
              
                if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))//记录已存在
                {
                    ConfirmBill(roductInBillDto.Id);//提交
                }
            }
            return Content("9");
        }
        #endregion
        #region 查看明细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id,string orgCode,bool isConfirm=false)
        {
            var billModel = operationServiceImpl.GetReturnBill(id);
            ViewBag.IsConfirm = isConfirm;
            ViewBag.orgCode = orgCode;
          return View(billModel);
        }
        #endregion
        #region 添加退货
        [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode, Guid? id)
        {

            ReturnBillDto billModel = null;

            if (id == null || !id.HasValue)
            {
               

               var NO = new BusinessBillNoCreator().CreateReturnNextNO();

               var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
               var wareHouse = initSysData.Values.FirstOrDefault();

               billModel = new ReturnBillDto
               {
                   ReturnBillNo = NO,
                   StorehouseName = wareHouse.StorehouseName,
                   StorehouseID = wareHouse.Id
               };//, DeliveryName = org.Name, DeliveryID =org.Id 
                ViewBag.BillId = "";
            }
            else
            {
                Guid billId;
                Guid.TryParse(id.ToString(), out billId);
                billModel = operationServiceImpl.GetReturnBill(billId);
                ViewBag.BillId = billId.ToString();
            }
            ViewBag.TempId = Guid.NewGuid();
            ViewBag.orgCode = orgCode;
            billModel.ReturnTime = DateTime.Today;

            #region 新厂和老厂的收货单位都为成都,现在其它的只能是深圳
            if (orgCode == SystemConfig.ChengDuCode)//退厂无法确定
            {
                //var cdinitSysData = DataInit.GetOrgAndDefaultWareHourse(SystemConfig.ChengDuCode);//初始化默认组织机构和仓库
                //var cdorg = cdinitSysData.Keys.FirstOrDefault();
                //billModel.DeliveryName = cdorg.Name;
                //billModel.DeliveryID = cdorg.Id;
            }
            else
            {
                var cdinitSysData = DataInit.GetOrgAndDefaultWareHourse(SystemConfig.ChengDuCode);//初始化默认收货组织机构和仓库
                var cdorg = cdinitSysData.Keys.FirstOrDefault();
                billModel.DeliveryName = cdorg.Name;
                billModel.DeliveryID = cdorg.Id;
            }
            #endregion

            return View(billModel);

        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ReturnBillDto roductInBillDto)
        {

            #region 弹出框数据获取
            var model = new ProductCheckBillModel();
            //仓库ID
            var whId = model.GetRequestFormValues(this.HttpContext, "StorehouseName_val");
            if (!Guid.Empty.Equals(whId))
            {
                roductInBillDto.StorehouseID = whId;
            }
            //退货人
            var ReturnId = model.GetRequestFormValues(this.HttpContext, "ReturnBillorName_val");
            if (!Guid.Empty.Equals(ReturnId))
            {
                roductInBillDto.ReturnBillorID = ReturnId;
            }
            //送货人
            var SenderId = model.GetRequestFormValues(this.HttpContext, "SenderName_val");
            if (!Guid.Empty.Equals(SenderId))
            {
                roductInBillDto.SenderID = SenderId;
            }
            ////确认人
            //var AffirmorId = model.GetRequestFormValues(this.HttpContext, "AffirmorName_val");
            //if (!Guid.Empty.Equals(AffirmorId))
            //{
            //    roductInBillDto.AffirmorID = AffirmorId;
            //}
            #endregion
            #region 主数据行处理
            roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);


            #endregion
            #region 明细行数据处理


            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<ReturnBillDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
            detailItems.Each(item =>
            {
                item.ReturnBillID = checkId;
                if (item.ID == null || item.ID.Equals(Guid.Empty))
                {
                    item.ID = Guid.Empty;
                }
            });

            #endregion
            #region 数据验证
            if (roductInBillDto.ReturnBillorID == null || roductInBillDto.ReturnBillorID.Equals(Guid.Empty))
            {
                return Content("0");
            }
            if (roductInBillDto.SenderID == null || roductInBillDto.SenderID.Equals(Guid.Empty))
            {
                return Content("0");
            }
            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
                return Content("-1");
            }
            #endregion
            if (ModelState.IsValid)
            {
                try
                {
                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        var tempId = this.operationServiceImpl.UpdateReturnBill(roductInBillDto, detailItems);
                        return Content(tempId.ToString());
                    }
                    else
                    {
                       var tempId= operationServiceImpl.AddReturnBill(roductInBillDto, detailItems);
                       return Content(tempId.ToString());
                    }
                }
                catch (Exception ex)
                {
                    return Content("-2");
                }
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 审核
       
        [NoAuthorizated("Audit")]
        public ActionResult Audit(Guid billId,string orgCode)
        {
            if (!billId.Equals(Guid.Empty))
            {
                Guid loginUserID = UserModel.GetLoginUserId(this.HttpContext);
                var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                var wareHouse = initSysData.Values.FirstOrDefault();
                this.operationServiceImpl.Audit(billId, loginUserID, new BusinessBillNoCreator().CreateInNextNO(), SystemConfig.BuinessBillNOLength, orgCode == SystemConfig.ChengDuCode, wareHouse.Id);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 确认
        public ActionResult Confirm()
        {
            return View();
        }
        //确认提交
        [NoAuthorizated("Confirm")]
        public ActionResult ConfirmBill(Guid billId)
        {
            if (!billId.Equals(Guid.Empty))
            {
                Guid loginUserID = UserModel.GetLoginUserId(this.HttpContext);
               this.operationServiceImpl.Confirm(billId, loginUserID);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 更新至库存
        [NoAuthorizated("UpdateToStock")]
        public ActionResult UpdateToStock(Guid billId, string ids)
        {

            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                operationServiceImpl.UpdateToStock(billId, guidIds);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 删除订单明细（假删除）
        [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId, string ids)
        {

            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                operationServiceImpl.ConvertReturnBillDeleteState(billId, guidIds);
                return Content("9");
            }
            else
            {
                operationServiceImpl.ConvertReturnBillDeleteState(billId);
                return Content("9");
            }

            return Content("0");
        }
        #endregion
        #region 获取退货列表数据
        //暂时获取所有数据
        [NoAuthorizated("GetJsonOfDatas")]
        public ActionResult GetJsonOfDatas()
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            var productBills = operationServiceImpl.GetReturnBills(1, 100);
            if (productBills != null && productBills.Count() != 0)
            {
                var jsonResult = productBills.Select(u =>
                {
                    u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                    u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                 //   u.c = u.CheckState > 0 ? "已审核" : "未审核";
                    return u;
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + productBills.Count() + "\"}";
                return Content(target);
            }
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetReturnBills(this.HttpContext));
        }
        /// <summary>
        /// 根据退货ID，获得退货所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
         [NoAuthorizated("GetJsonOfBillDetails")]
        public ActionResult GetJsonOfBillDetails(Guid billId)
        {

            #region EF的查询，效率低下，故暂时放弃不用
            //var billDetails = operationServiceImpl.GetReturnBillDetails(billId).Where(p => p.Deleted == 0).ToList();
            //if (billDetails != null && billDetails.Count() != 0)
            //{
            //    var jsonResult = billDetails.Select(b => { b.DeleteState = b.Deleted == 0 ? "正常" : "已删除"; return b; });
            //    var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //    target = "{\"Rows\":" + target + ",\"Total\":\"" + billDetails.Count() + "\"}";
            //    return Content(target);
            //}
            //return Content("");
            #endregion
            if (!billId.Equals(Guid.Empty))
            {
                return Content(new BLLQuery().GetReturnDetails(billId));
            }
            else
            {
                return Content("");
            }

           

        }
        #endregion
        #region 深圳业务
         public ActionResult SZIndex()
         {
             ViewBag.orgCode = SystemConfig.ShengZhenCode;
             return View("Index");
         }
        
         #endregion
        #region 退新厂确认
         //确认退新厂
         public ActionResult XCConfirm()
         {
             return View();
         } 
        #endregion
        #region 退新厂确认
         //确认老新厂
         public ActionResult LCConfirm()
         {
             return View();
         }
         #endregion
    }
}
